import { showModal, toast } from '~/composables/util'
import { logout, updatepassword } from '~/api/manager'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { ref, reactive } from 'vue'

export function useRepassword() {
    const router = useRouter()
    const store = useStore()

    const formDrawerRef = ref(null)
    const formRef = ref(null)

    const form = reactive({
        password: '',
        newPassword: '',

    })

    const onSubmit = () => {
        formRef.value.validate((valid) => {
            if (!valid) {
                return false
            }
            formDrawerRef.value.showLoading()
            updatepassword(form)
                .then((res) => {
                    toast("修改密码成功，请重新登录！")
                    store.dispatch("logout")
                    router.push("/logout")
                })
                .finally(() => {
                    formDrawerRef.value.hideLoading()
                })
        })
    }

    const rules = {
        
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
        ],
        newPassword: [
            { required: true, message: '请输入确认密码', trigger: 'blur' },
        ],
    }

    const openRePassword = () => {
        //清空数据
        form.password = ''
        form.newPassword = ''
        if (formRef.value) formRef.value.resetFields()
        formDrawerRef.value.open()
    }
    return {
        formDrawerRef,
        formRef,
        form,
        rules,
        onSubmit,
        openRePassword
    }
}

export function useLogout() {
    const router = useRouter()
    const store = useStore()
    
    function handleLogout() {
        showModal("是否要退出登录？")
            .then(res => {
                logout()
                    .finally(() => {
                        // 移除token
    
                        // 清除用户状态 vuex
                        store.dispatch("logout")
                        // 跳转登录页
                        router.push("/login")
                        // 提示退出
                        toast("退出登录成功")
                    })
            })
    
    }

    return {
        handleLogout,
    }
}